import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Table,
  Tag,
  Spin,
  message,
  Typography,
  Space,
  Button,
  Alert,
  List,
  Avatar
} from 'antd';
import {
  CloudServerOutlined,
  DatabaseOutlined,
  CloudOutlined,
  SafetyOutlined,
  ReloadOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined
} from '@ant-design/icons';
import { Line, Gauge, Column } from '@ant-design/charts';
import dayjs from 'dayjs';

const { Title, Text } = Typography;

const SystemDashboard = () => {
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  
  // 系统状态数据
  const [systemStatus, setSystemStatus] = useState({
    serverStatus: 'healthy',
    databaseStatus: 'healthy',
    cacheStatus: 'healthy',
    apiStatus: 'healthy',
    uptime: '7天12小时30分钟'
  });
  
  // 性能指标
  const [performanceMetrics, setPerformanceMetrics] = useState({
    cpuUsage: 45,
    memoryUsage: 68,
    diskUsage: 32,
    networkIn: 1024,
    networkOut: 2048,
    responseTime: 120
  });
  
  // 系统日志
  const [systemLogs, setSystemLogs] = useState([]);
  
  // 错误统计
  const [errorStats, setErrorStats] = useState([]);
  
  // API调用统计
  const [apiStats, setApiStats] = useState([]);

  // 加载系统状态
  const loadSystemStatus = async () => {
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 模拟系统状态数据
      setSystemStatus({
        serverStatus: Math.random() > 0.1 ? 'healthy' : 'warning',
        databaseStatus: Math.random() > 0.05 ? 'healthy' : 'error',
        cacheStatus: Math.random() > 0.1 ? 'healthy' : 'warning',
        apiStatus: Math.random() > 0.1 ? 'healthy' : 'warning',
        uptime: `${Math.floor(Math.random() * 30)}天${Math.floor(Math.random() * 24)}小时${Math.floor(Math.random() * 60)}分钟`
      });
    } catch (error) {
      console.error('加载系统状态失败:', error);
      message.error('加载系统状态失败');
    }
  };

  // 加载性能指标
  const loadPerformanceMetrics = async () => {
    try {
      // 模拟性能数据
      setPerformanceMetrics({
        cpuUsage: Math.floor(Math.random() * 80) + 10,
        memoryUsage: Math.floor(Math.random() * 90) + 10,
        diskUsage: Math.floor(Math.random() * 70) + 10,
        networkIn: Math.floor(Math.random() * 5000) + 500,
        networkOut: Math.floor(Math.random() * 8000) + 1000,
        responseTime: Math.floor(Math.random() * 200) + 50
      });
    } catch (error) {
      console.error('加载性能指标失败:', error);
      message.error('加载性能指标失败');
    }
  };

  // 加载系统日志
  const loadSystemLogs = async () => {
    try {
      // 模拟系统日志数据
      const logs = [];
      const logTypes = ['INFO', 'WARN', 'ERROR', 'DEBUG'];
      const logMessages = [
        '用户登录成功',
        '数据库连接超时',
        '缓存清理完成',
        'API调用频率过高',
        '系统备份完成',
        '内存使用率告警',
        '新用户注册',
        '订单创建成功'
      ];
      
      for (let i = 0; i < 20; i++) {
        logs.push({
          id: i + 1,
          timestamp: dayjs().subtract(Math.floor(Math.random() * 1440), 'minute').format('YYYY-MM-DD HH:mm:ss'),
          level: logTypes[Math.floor(Math.random() * logTypes.length)],
          message: logMessages[Math.floor(Math.random() * logMessages.length)],
          source: `Service-${Math.floor(Math.random() * 5) + 1}`
        });
      }
      
      setSystemLogs(logs.sort((a, b) => dayjs(b.timestamp).unix() - dayjs(a.timestamp).unix()));
    } catch (error) {
      console.error('加载系统日志失败:', error);
      message.error('加载系统日志失败');
    }
  };

  // 加载错误统计
  const loadErrorStats = async () => {
    try {
      // 模拟错误统计数据
      const stats = [];
      for (let i = 0; i < 7; i++) {
        stats.push({
          date: dayjs().subtract(i, 'day').format('MM-DD'),
          errors: Math.floor(Math.random() * 50),
          warnings: Math.floor(Math.random() * 100)
        });
      }
      setErrorStats(stats.reverse());
    } catch (error) {
      console.error('加载错误统计失败:', error);
      message.error('加载错误统计失败');
    }
  };

  // 加载API统计
  const loadApiStats = async () => {
    try {
      // 模拟API统计数据
      const apis = [
        { endpoint: '/api/products', calls: 1250, avgTime: 120, errorRate: 2.1 },
        { endpoint: '/api/orders', calls: 890, avgTime: 180, errorRate: 1.5 },
        { endpoint: '/api/users', calls: 650, avgTime: 95, errorRate: 0.8 },
        { endpoint: '/api/analytics', calls: 420, avgTime: 250, errorRate: 3.2 },
        { endpoint: '/api/auth', calls: 380, avgTime: 80, errorRate: 1.2 }
      ];
      setApiStats(apis);
    } catch (error) {
      console.error('加载API统计失败:', error);
      message.error('加载API统计失败');
    }
  };

  // 刷新所有数据
  const handleRefresh = async () => {
    setRefreshing(true);
    try {
      await Promise.all([
        loadSystemStatus(),
        loadPerformanceMetrics(),
        loadSystemLogs(),
        loadErrorStats(),
        loadApiStats()
      ]);
      message.success('数据刷新成功');
    } catch (error) {
      message.error('数据刷新失败');
    } finally {
      setRefreshing(false);
    }
  };

  // 初始加载
  useEffect(() => {
    const loadData = async () => {
      setLoading(true);
      try {
        await Promise.all([
          loadSystemStatus(),
          loadPerformanceMetrics(),
          loadSystemLogs(),
          loadErrorStats(),
          loadApiStats()
        ]);
      } finally {
        setLoading(false);
      }
    };
    
    loadData();
    
    // 设置定时刷新
    const interval = setInterval(() => {
      loadPerformanceMetrics();
    }, 30000); // 30秒刷新一次性能数据
    
    return () => clearInterval(interval);
  }, []);

  // 获取状态颜色
  const getStatusColor = (status) => {
    switch (status) {
      case 'healthy': return 'success';
      case 'warning': return 'warning';
      case 'error': return 'error';
      default: return 'default';
    }
  };

  // 获取状态图标
  const getStatusIcon = (status) => {
    switch (status) {
      case 'healthy': return <CheckCircleOutlined />;
      case 'warning': return <WarningOutlined />;
      case 'error': return <ClockCircleOutlined />;
      default: return <CheckCircleOutlined />;
    }
  };

  // 获取日志级别颜色
  const getLogLevelColor = (level) => {
    switch (level) {
      case 'ERROR': return 'red';
      case 'WARN': return 'orange';
      case 'INFO': return 'blue';
      case 'DEBUG': return 'default';
      default: return 'default';
    }
  };

  // 系统日志表格列
  const logColumns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      width: 150
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: 80,
      render: (level) => (
        <Tag color={getLogLevelColor(level)}>{level}</Tag>
      )
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      width: 100
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
      ellipsis: true
    }
  ];

  // API统计表格列
  const apiColumns = [
    {
      title: 'API端点',
      dataIndex: 'endpoint',
      key: 'endpoint'
    },
    {
      title: '调用次数',
      dataIndex: 'calls',
      key: 'calls',
      sorter: (a, b) => a.calls - b.calls
    },
    {
      title: '平均响应时间(ms)',
      dataIndex: 'avgTime',
      key: 'avgTime',
      sorter: (a, b) => a.avgTime - b.avgTime
    },
    {
      title: '错误率(%)',
      dataIndex: 'errorRate',
      key: 'errorRate',
      render: (rate) => (
        <Tag color={rate > 3 ? 'red' : rate > 1 ? 'orange' : 'green'}>
          {rate}%
        </Tag>
      ),
      sorter: (a, b) => a.errorRate - b.errorRate
    }
  ];

  // CPU使用率仪表盘配置
  const cpuGaugeConfig = {
    percent: performanceMetrics.cpuUsage / 100,
    range: {
      color: performanceMetrics.cpuUsage > 80 ? '#ff4d4f' : performanceMetrics.cpuUsage > 60 ? '#faad14' : '#52c41a'
    },
    indicator: {
      pointer: {
        style: {
          stroke: '#D0D0D0'
        }
      },
      pin: {
        style: {
          stroke: '#D0D0D0'
        }
      }
    },
    statistic: {
      content: {
        style: {
          fontSize: '36px',
          lineHeight: '36px'
        },
        formatter: () => `${performanceMetrics.cpuUsage}%`
      }
    }
  };

  // 错误统计图配置
  const errorStatsConfig = {
    data: errorStats,
    xField: 'date',
    yField: 'errors',
    color: '#ff4d4f',
    columnWidthRatio: 0.6,
    meta: {
      errors: {
        alias: '错误数量'
      }
    }
  };

  return (
    <div className="system-dashboard">
      {/* 页面头部 */}
      <div className="page-header">
        <div className="header-content">
          <Title level={2}>系统数据看板</Title>
          <Button
            icon={<ReloadOutlined />}
            onClick={handleRefresh}
            loading={refreshing}
          >
            刷新
          </Button>
        </div>
      </div>

      <Spin spinning={loading}>
        {/* 系统状态概览 */}
        <Row gutter={[16, 16]} className="status-cards">
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="服务器状态"
                value={systemStatus.serverStatus === 'healthy' ? '正常' : '异常'}
                prefix={getStatusIcon(systemStatus.serverStatus)}
                valueStyle={{ color: systemStatus.serverStatus === 'healthy' ? '#52c41a' : '#ff4d4f' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="数据库状态"
                value={systemStatus.databaseStatus === 'healthy' ? '正常' : '异常'}
                prefix={<DatabaseOutlined />}
                valueStyle={{ color: systemStatus.databaseStatus === 'healthy' ? '#52c41a' : '#ff4d4f' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="缓存状态"
                value={systemStatus.cacheStatus === 'healthy' ? '正常' : '异常'}
                prefix={<CloudOutlined />}
                valueStyle={{ color: systemStatus.cacheStatus === 'healthy' ? '#52c41a' : '#ff4d4f' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={12} lg={6}>
            <Card>
              <Statistic
                title="运行时间"
                value={systemStatus.uptime}
                prefix={<ClockCircleOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 性能指标 */}
        <Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
          <Col xs={24} lg={8}>
            <Card title="CPU使用率" className="performance-card">
              <Gauge {...cpuGaugeConfig} height={200} />
            </Card>
          </Col>
          <Col xs={24} lg={8}>
            <Card title="内存使用情况" className="performance-card">
              <div style={{ padding: '20px 0' }}>
                <Progress
                  type="circle"
                  percent={performanceMetrics.memoryUsage}
                  strokeColor={performanceMetrics.memoryUsage > 80 ? '#ff4d4f' : '#52c41a'}
                  size={150}
                  format={(percent) => `${percent}%`}
                />
              </div>
            </Card>
          </Col>
          <Col xs={24} lg={8}>
            <Card title="磁盘使用情况" className="performance-card">
              <div style={{ padding: '20px 0' }}>
                <Progress
                  type="circle"
                  percent={performanceMetrics.diskUsage}
                  strokeColor={performanceMetrics.diskUsage > 80 ? '#ff4d4f' : '#52c41a'}
                  size={150}
                  format={(percent) => `${percent}%`}
                />
              </div>
            </Card>
          </Col>
        </Row>

        {/* 网络和响应时间 */}
        <Row gutter={[16, 16]} style={{ marginTop: '16px' }}>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="网络入流量"
                value={performanceMetrics.networkIn}
                suffix="KB/s"
                prefix={<CloudOutlined />}
                valueStyle={{ color: '#1890ff' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="网络出流量"
                value={performanceMetrics.networkOut}
                suffix="KB/s"
                prefix={<CloudOutlined />}
                valueStyle={{ color: '#52c41a' }}
              />
            </Card>
          </Col>
          <Col xs={24} sm={8}>
            <Card>
              <Statistic
                title="平均响应时间"
                value={performanceMetrics.responseTime}
                suffix="ms"
                prefix={<CloudServerOutlined />}
                valueStyle={{ color: performanceMetrics.responseTime > 200 ? '#ff4d4f' : '#52c41a' }}
              />
            </Card>
          </Col>
        </Row>

        {/* 错误统计和API统计 */}
        <Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
          <Col xs={24} lg={12}>
            <Card title="错误统计（最近7天）" className="chart-card">
              <Column {...errorStatsConfig} height={300} />
            </Card>
          </Col>
          <Col xs={24} lg={12}>
            <Card title="API调用统计" className="table-card">
              <Table
                columns={apiColumns}
                dataSource={apiStats}
                pagination={false}
                size="small"
                scroll={{ y: 300 }}
                rowKey="endpoint"
              />
            </Card>
          </Col>
        </Row>

        {/* 系统日志 */}
        <Row gutter={[16, 16]} style={{ marginTop: '24px' }}>
          <Col span={24}>
            <Card title="系统日志（最新20条）" className="log-card">
              <Table
                columns={logColumns}
                dataSource={systemLogs}
                pagination={false}
                size="small"
                scroll={{ y: 400 }}
                rowKey="id"
              />
            </Card>
          </Col>
        </Row>
      </Spin>
    </div>
  );
};

export default SystemDashboard;